package cn.zifangsky.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpUtil {
	
	public static  String get(String url,Map<String, Object> parm) throws Exception {
        String content = null;
        URLConnection urlConnection = new URL(url).openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", parm.get("Authorization").toString());
        //连接
        connection.connect();
        //得到响应码
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
                    (connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder bs = new StringBuilder();
            String l;
            while ((l = bufferedReader.readLine()) != null) {
                bs.append(l).append("\n");
            }
            content = bs.toString();
        }
        return content;
    }
	
	//发送请求并将params的参数加入请求体body中
	  public static String httpRequest(String requestUrl, Map<String, Object> params, String requestMethod) {
	        String result = null;
	        StringBuilder paramsStr = new StringBuilder();
	        for(String key:params.keySet()) {
	        	Object value = params.get(key);
	            try {
	                paramsStr.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(value), "UTF-8")).append("&");
	            } catch (UnsupportedEncodingException e) {
	                e.printStackTrace();
	            }
	        }
//	        params.forEach((key, value) -> {
//
//	        });
	        if("POST".equals(requestMethod)) {

	            RequestConfig requestConfig = RequestConfig.custom()
	                    .setSocketTimeout(30 * 1000)
	                    .setConnectTimeout(30 * 1000)
	                    .setConnectionRequestTimeout(30 * 1000)
	                    .build();
	            HttpPost httpPost = new HttpPost(requestUrl);
	            httpPost.setConfig(requestConfig);
	            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
	            httpPost.setEntity(new StringEntity(paramsStr.substring(0, paramsStr.length() - 1), StandardCharsets.UTF_8));
	


	            try (
//	            		CloseableHttpClient httpclient = HttpClients.custom().
//	        					setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
//	        					.setSSLSocketFactory(buildSslSocketFactoryForIgnoreCertificate())
//	        					.build();
	            		//CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setSSLSocketFactory(buildSslSocketFactoryForIgnoreCertificate()).build();
	            		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setSSLContext(getSSLContext()).build();

	            		CloseableHttpResponse response = httpclient.execute(httpPost)) 
	            {

	                HttpEntity entity = response.getEntity();
	                result = EntityUtils.toString(entity, "UTF-8");
	            } catch (Exception e) {
	                e.printStackTrace();
	            }

	        } else if("GET".equals(requestMethod)) {

	            String requestUrlWithParam = requestUrl + "?" + paramsStr.substring(0, paramsStr.length() - 1);
	            HttpGet httpGet = new HttpGet(requestUrlWithParam);
	            try(CloseableHttpClient httpClient = HttpClients.createDefault();
	                CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
	                HttpEntity httpEntity = httpResponse.getEntity();
	                result = EntityUtils.toString(httpEntity, "UTF-8");
	            } catch (IOException e) {
	                e.printStackTrace();
	            }

	        }

	        return result;
	    }
	  
	  private static SSLSocketFactory buildSslSocketFactoryForIgnoreCertificate() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {

			X509TrustManager trustManager = new X509TrustManager() {

				public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
						throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
						throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}


			};
			//Security.setProperty("jdk.tls.client.protocols", "TLSv1,TLSv1.1,TLSv1.2");
			Security.addProvider(new BouncyCastleProvider());
			Security.addProvider(new BouncyCastleJsseProvider());
			SSLContext sslcontext = SSLContext.getInstance("TLSv1.2",BouncyCastleJsseProvider.PROVIDER_NAME);

			sslcontext.init(null, new TrustManager[]{trustManager}, null);

			SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext);

			sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			return sslSocketFactory;

		}


	private static SSLContext getSSLContext() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {

		X509TrustManager trustManager = new X509TrustManager() {

			public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
					throws CertificateException {
				// TODO Auto-generated method stub

			}

			public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
					throws CertificateException {
				// TODO Auto-generated method stub

			}

			public X509Certificate[] getAcceptedIssuers() {
				// TODO Auto-generated method stub
				return null;
			}


		};
		//Security.setProperty("jdk.tls.client.protocols", "TLSv1,TLSv1.1,TLSv1.2");
		Security.addProvider(new BouncyCastleProvider());
		Security.addProvider(new BouncyCastleJsseProvider());
		SSLContext sslcontext = SSLContext.getInstance("TLSv1.2",BouncyCastleJsseProvider.PROVIDER_NAME);

		sslcontext.init(null, new TrustManager[]{trustManager}, null);

		//SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext);

		//sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

		return sslcontext;

	}

}
